package com.xjscrm.console.service.customer.groupSend.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.utils.ww.WwApiUtil;
import com.xjscrm.common.utils.ww.dto.WwCreateBulkSendDTO;
import com.xjscrm.common.utils.ww.dto.WwCreateBulkSendResultDTO;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.console.config.datasource.DynamicDataSourceContextHolder;
import com.xjscrm.console.entity.WwCorp;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.groupSend.*;
import com.xjscrm.console.param.user.ChildMerchatDto;
import com.xjscrm.console.param.wwCustomer.CustomerQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.common.corpapplication.CorpApplicationService;
import com.xjscrm.console.service.common.user.UserService;
import com.xjscrm.console.service.customer.childUser.ChildMerchatService;
import com.xjscrm.console.service.customer.groupSend.SpeedGroupSendService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import com.xjscrm.console.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SpeedGroupSendServiceImpl implements SpeedGroupSendService {

    private static Logger logger = LoggerFactory.getLogger(SpeedGroupSendServiceImpl.class);

    @Autowired
    private SpeedGroupSendTaskMapper speedGroupSendTaskMapper;

    @Autowired
    private SpeedGroupSendTaskCustomerMapper speedGroupSendTaskCustomerMapper;

    @Autowired
    private SpeedGroupSendTaskDeviceMapper speedGroupSendTaskDeviceMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Autowired
    private WwCorpMapper wwCorpMapper;
    @Autowired
    private CorpApplicationService corpApplicationService;

    @Autowired
    private SpeedGroupSendJobMapper speedGroupSendJobMapper;

    @Autowired
    private SpeedGroupSendJobDeviceMapper speedGroupSendJobDeviceMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ChildMerchatService childMerchatService;

    @Autowired
    private BlackListMapper blackListMapper;

    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSpeedGroupSendTask(SpeedGroupSendTaskDto speedGroupSendTaskDto) {

        if (speedGroupSendTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList() == null || speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //保存极速群发任务
        SpeedGroupSendTask speedGroupSendTask = new SpeedGroupSendTask();
        BeanUtil.copyProperties(speedGroupSendTaskDto, speedGroupSendTask);
        int time = DateUtil.getTime();
        long id = IdWorker.getId();
        speedGroupSendTask.setId(id);
        speedGroupSendTask.setCreateTime(time);
        speedGroupSendTask.setUpdateTime(time);
        speedGroupSendTaskMapper.insert(speedGroupSendTask);

        //保存极速群发任务和呵护关系
        if (speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList() != null && !speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList().isEmpty()) {
            for (SpeedGroupSendTaskCustomerDto speedGroupSendTaskCustomerDto : speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList()) {
                SpeedGroupSendTaskCustomer speedGroupSendTaskCustomer = new SpeedGroupSendTaskCustomer();
                BeanUtil.copyProperties(speedGroupSendTaskCustomerDto, speedGroupSendTaskCustomer);
                speedGroupSendTaskCustomer.setTaskId(id);
                speedGroupSendTaskCustomer.setMerId(speedGroupSendTask.getMerId());
                speedGroupSendTaskCustomerMapper.add(speedGroupSendTaskCustomer);
            }
        }


        //保存极速群发任务和机器人关系
        for (SpeedGroupSendTaskDeviceDto speedGroupSendTaskDeviceDto : speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList()) {
            SpeedGroupSendTaskDevice speedGroupSendTaskDevice = new SpeedGroupSendTaskDevice();
            BeanUtil.copyProperties(speedGroupSendTaskDeviceDto, speedGroupSendTaskDevice);
            speedGroupSendTaskDevice.setTaskId(id);
            speedGroupSendTaskDevice.setMerId(speedGroupSendTask.getMerId());
            speedGroupSendTaskDeviceMapper.add(speedGroupSendTaskDevice);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSpeedGroupSendTask(SpeedGroupSendTaskDto speedGroupSendTaskDto) {
        if (speedGroupSendTaskDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (speedGroupSendTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList() == null || speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (speedGroupSendTaskDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "立即发送类型不支持编辑");
        }

        SpeedGroupSendTask speedGroupSendTask = speedGroupSendTaskMapper.getById(speedGroupSendTaskDto.getId(), speedGroupSendTaskDto.getMerId());
        if (speedGroupSendTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }
        //修改群发任务
        BeanUtil.copyProperties(speedGroupSendTaskDto, speedGroupSendTask);
        speedGroupSendTask.setStatus(1);
        speedGroupSendTaskMapper.update(speedGroupSendTask);

        //查询群发任务和客户/群关系 删除旧数据
        SpeedGroupSendTaskCustomerQuery spendGroupSendTaskCustomerQuery = new SpeedGroupSendTaskCustomerQuery();
        spendGroupSendTaskCustomerQuery.setMerId(speedGroupSendTask.getMerId());
        spendGroupSendTaskCustomerQuery.setTaskId(speedGroupSendTask.getId());
        List<SpeedGroupSendTaskCustomerVo> speedGroupSendTaskCustomerVoList = speedGroupSendTaskCustomerMapper.getSpendGroupSendTaskCustomerList(spendGroupSendTaskCustomerQuery);
        if (speedGroupSendTaskCustomerVoList != null && !speedGroupSendTaskCustomerVoList.isEmpty()) {
            speedGroupSendTaskCustomerVoList.forEach(it -> speedGroupSendTaskCustomerMapper.deleById(it.getId(), it.getMerId()));
        }
        //保存群发任务和客户关系
        if (speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList() != null && !speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList().isEmpty()) {
            for (SpeedGroupSendTaskCustomerDto speedGroupSendTaskCustomerDto : speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList()) {
                SpeedGroupSendTaskCustomer speedGroupSendTaskCustomer = new SpeedGroupSendTaskCustomer();
                BeanUtil.copyProperties(speedGroupSendTaskCustomerDto, speedGroupSendTaskCustomer);
                speedGroupSendTaskCustomer.setTaskId(speedGroupSendTask.getId());
                speedGroupSendTaskCustomer.setMerId(speedGroupSendTask.getMerId());
                speedGroupSendTaskCustomerMapper.add(speedGroupSendTaskCustomer);
            }
        }

        //查询群发任务和机器人关系 删除旧数据
        SpeedGroupSendDeviceQuery speedGroupSendDeviceQuery = new SpeedGroupSendDeviceQuery();
        speedGroupSendDeviceQuery.setMerId(speedGroupSendTask.getMerId());
        speedGroupSendDeviceQuery.setTaskId(speedGroupSendTask.getId());
        List<SpeedGroupSendDeviceVo> speedGroupSendDeviceVoList = speedGroupSendTaskDeviceMapper.getSpeedGroupSendDeviceList(speedGroupSendDeviceQuery);
        if (speedGroupSendDeviceVoList != null && !speedGroupSendDeviceVoList.isEmpty()) {
            speedGroupSendDeviceVoList.forEach(it -> speedGroupSendTaskDeviceMapper.deleById(it.getId(), it.getMerId()));
        }

        //保存极速群发任务和机器人关系
        for (SpeedGroupSendTaskDeviceDto speedGroupSendTaskDeviceDto : speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList()) {
            SpeedGroupSendTaskDevice speedGroupSendTaskDevice = new SpeedGroupSendTaskDevice();
            BeanUtil.copyProperties(speedGroupSendTaskDeviceDto, speedGroupSendTaskDevice);
            speedGroupSendTaskDevice.setTaskId(speedGroupSendTask.getId());
            speedGroupSendTaskDevice.setMerId(speedGroupSendTask.getMerId());
            speedGroupSendTaskDeviceMapper.add(speedGroupSendTaskDevice);
        }
    }

    @Override
    public Object getSpeedGroupSendTaskList(SpeedGroupSendTaskQuery speedGroupSendTaskQuery) {
        if (speedGroupSendTaskQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String orderBy = OrderByUtil.getOrderBy(speedGroupSendTaskQuery.getOrderByField(), speedGroupSendTaskQuery.isAsc());
        PageHelper.startPage(speedGroupSendTaskQuery.getCurrent(), speedGroupSendTaskQuery.getSize(), orderBy);
        List<SpeedGroupSendTaskVo> speedGroupSendTaskVoList = speedGroupSendTaskMapper.getSpeedGroupSendTaskList(speedGroupSendTaskQuery);

        if (speedGroupSendTaskVoList != null && !speedGroupSendTaskVoList.isEmpty()) {
            //获取机器人
            speedGroupSendTaskVoList.forEach(it -> {
                //获取关联的机器人ID
                SpeedGroupSendDeviceQuery speedGroupSendDeviceQuery = new SpeedGroupSendDeviceQuery();
                speedGroupSendDeviceQuery.setMerId(it.getMerId());
                speedGroupSendDeviceQuery.setTaskId(it.getId());
                List<SpeedGroupSendDeviceVo> speedGroupSendDeviceVoList = speedGroupSendTaskDeviceMapper.getSpeedGroupSendDeviceList(speedGroupSendDeviceQuery);
                if (speedGroupSendDeviceVoList != null && !speedGroupSendDeviceVoList.isEmpty()) {
                    List<Long> deviceUniqueIds = speedGroupSendDeviceVoList.stream().map(SpeedGroupSendDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
                    //获取关联机器人的昵称
                    WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
                    wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                    wwDeviceQuery.setMerId(it.getMerId());
                    List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                    if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
                        List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                        it.setDeviceNames(deviceNames);
                    }
                }
            });
        }

        return new MyPageInfo<>(speedGroupSendTaskVoList);
    }

    @Override
    public Object getSpeedGroupSendTaskDetail(SpeedGroupSendTaskDto speedGroupSendTaskDto) {
        if (speedGroupSendTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (speedGroupSendTaskDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        SpeedGroupSendTask speedGroupSendTask = speedGroupSendTaskMapper.getById(speedGroupSendTaskDto.getId(), speedGroupSendTaskDto.getMerId());
        if (speedGroupSendTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        SpeedGroupSendTaskVo speedGroupSendTaskVo = new SpeedGroupSendTaskVo();
        BeanUtil.copyProperties(speedGroupSendTask, speedGroupSendTaskVo);

        //获取关联的机器人ID
        SpeedGroupSendDeviceQuery speedGroupSendDeviceQuery = new SpeedGroupSendDeviceQuery();
        speedGroupSendDeviceQuery.setMerId(speedGroupSendTask.getMerId());
        speedGroupSendDeviceQuery.setTaskId(speedGroupSendTask.getId());
        List<SpeedGroupSendDeviceVo> speedGroupSendDeviceVoList = speedGroupSendTaskDeviceMapper.getSpeedGroupSendDeviceList(speedGroupSendDeviceQuery);
        if (speedGroupSendDeviceVoList != null && !speedGroupSendDeviceVoList.isEmpty()) {
            List<Long> deviceUniqueIds = speedGroupSendDeviceVoList.stream().map(SpeedGroupSendDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
            //获取关联机器人的昵称
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
            wwDeviceQuery.setMerId(speedGroupSendTask.getMerId());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
                speedGroupSendTaskVo.setWwDeviceVoList(wwDeviceList);
                List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                speedGroupSendTaskVo.setDeviceNames(deviceNames);
            }
        }


        //发给对象wxid（私聊就是客户wxid,群聊就是群wxid）
        List<String> sendWxids = new ArrayList<>();
        SpeedGroupSendTaskCustomerQuery speedGroupSendTaskCustomerQuery = new SpeedGroupSendTaskCustomerQuery();
        speedGroupSendTaskCustomerQuery.setMerId(speedGroupSendTask.getMerId());
        speedGroupSendTaskCustomerQuery.setTaskId(speedGroupSendTask.getId());
        List<SpeedGroupSendTaskCustomerVo> speedGroupSendTaskCustomerVoList = speedGroupSendTaskCustomerMapper.getSpendGroupSendTaskCustomerList(speedGroupSendTaskCustomerQuery);
        if (speedGroupSendTaskCustomerVoList != null && !speedGroupSendTaskCustomerVoList.isEmpty()) {

            for (SpeedGroupSendTaskCustomerVo speedGroupSendTaskCustomerVo : speedGroupSendTaskCustomerVoList) {
                if (speedGroupSendTask.getCustomerType() != null && speedGroupSendTask.getCustomerType().equals(2)) {
                    List<WwCustomerVo> wwCustomerVoList = new ArrayList<>();
                    CustomerQuery customerQuery = new CustomerQuery();
                    customerQuery.setMerId(speedGroupSendTask.getMerId());
                    customerQuery.setWxids(sendWxids);
                    WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(speedGroupSendTaskCustomerVo.getSendWxid(), speedGroupSendTaskCustomerVo.getDeviceUniqueId(), speedGroupSendTaskCustomerVo.getMerId());
                    if (wwCustomer != null) {
                        WwCustomerVo wwCustomerVo = new WwCustomerVo();
                        BeanUtil.copyProperties(wwCustomer, wwCustomerVo);
                        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), wwCustomer.getMerId());
                        if (wwDevice != null) {
                            wwCustomerVo.setDeviceName(wwDevice.getDeviceName());
                            wwCustomerVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                        }
                        wwCustomerVoList.add(wwCustomerVo);
                    }
                    speedGroupSendTaskVo.setWwCustomerVoList(wwCustomerVoList);
                }

                if (speedGroupSendTask.getGroupType() != null && speedGroupSendTask.getGroupType().equals(2)) {
                    List<WwGroupVo> wwGroupList = new ArrayList<>();
                    WwGroup wwGroup = wwGroupMapper.selectByGroupWxId(speedGroupSendTaskCustomerVo.getMerId(), speedGroupSendTaskCustomerVo.getDeviceUniqueId(), speedGroupSendTaskCustomerVo.getSendWxid());
                    if (wwGroup != null) {
                        WwGroupVo wwGroupVo = new WwGroupVo();
                        BeanUtil.copyProperties(wwGroup, wwGroupVo);
                        WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), wwGroup.getMerId());
                        if (wwDevice != null) {
                            wwGroupVo.setDeviceName(wwDevice.getDeviceName());
                            wwGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                        }
                        wwGroupList.add(wwGroupVo);
                    }
                    speedGroupSendTaskVo.setWwGroupVoList(wwGroupList);
                }
            }
            //获取企业名
            WwCorp wwCorp = wwCorpMapper.getByCorpId(speedGroupSendTask.getCorpId(), speedGroupSendTask.getMerId());
            if (wwCorp != null) {
                speedGroupSendTaskVo.setCorpName(wwCorp.getName());
            }


        }
        return speedGroupSendTaskVo;
    }


    @Override
    public void startAndStop(StartAndStopDto startAndStopDto) {

        if (startAndStopDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (startAndStopDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (startAndStopDto.getStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "状态不能为空");
        }
        SpeedGroupSendTask speedGroupSendTask = speedGroupSendTaskMapper.getById(startAndStopDto.getId(), startAndStopDto.getMerId());
        if (speedGroupSendTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        speedGroupSendTask.setStatus(startAndStopDto.getStatus());
        speedGroupSendTaskMapper.update(speedGroupSendTask);
    }

    @Override
    public void deleSpeedGroupSendTask(SpeedGroupSendTaskDto speedGroupSendTaskDto) {
        if (speedGroupSendTaskDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (speedGroupSendTaskDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        SpeedGroupSendTask speedGroupSendTask = speedGroupSendTaskMapper.getById(speedGroupSendTaskDto.getId(), speedGroupSendTaskDto.getMerId());
        if (speedGroupSendTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        //查询群发任务和客户/群关系 删除旧数据
        SpeedGroupSendTaskCustomerQuery spendGroupSendTaskCustomerQuery = new SpeedGroupSendTaskCustomerQuery();
        spendGroupSendTaskCustomerQuery.setMerId(speedGroupSendTask.getMerId());
        spendGroupSendTaskCustomerQuery.setTaskId(speedGroupSendTask.getId());
        List<SpeedGroupSendTaskCustomerVo> speedGroupSendTaskCustomerVoList = speedGroupSendTaskCustomerMapper.getSpendGroupSendTaskCustomerList(spendGroupSendTaskCustomerQuery);
        if (speedGroupSendTaskCustomerVoList != null && !speedGroupSendTaskCustomerVoList.isEmpty()) {
            speedGroupSendTaskCustomerVoList.forEach(it -> speedGroupSendTaskCustomerMapper.deleById(it.getId(), it.getMerId()));
        }

        //查询群发任务和机器人关系 删除旧数据
        SpeedGroupSendDeviceQuery speedGroupSendDeviceQuery = new SpeedGroupSendDeviceQuery();
        speedGroupSendDeviceQuery.setMerId(speedGroupSendTask.getMerId());
        speedGroupSendDeviceQuery.setTaskId(speedGroupSendTask.getId());
        List<SpeedGroupSendDeviceVo> speedGroupSendDeviceVoList = speedGroupSendTaskDeviceMapper.getSpeedGroupSendDeviceList(speedGroupSendDeviceQuery);
        if (speedGroupSendDeviceVoList != null && !speedGroupSendDeviceVoList.isEmpty()) {
            speedGroupSendDeviceVoList.forEach(it -> speedGroupSendTaskDeviceMapper.deleById(it.getId(), it.getMerId()));
        }

        //删除群发任务
        speedGroupSendTaskMapper.deleById(speedGroupSendTask.getId(), speedGroupSendTask.getMerId());
    }


    @Override
    public Object getSpeedGroupSendJobList(SpeedGroupSendJobQuery speedGroupSendJobQuery) {

        if (speedGroupSendJobQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String orderBy = OrderByUtil.getOrderBy(speedGroupSendJobQuery.getOrderByField(), speedGroupSendJobQuery.isAsc());
        PageHelper.startPage(speedGroupSendJobQuery.getCurrent(), speedGroupSendJobQuery.getSize(), orderBy);
        List<SpeedGroupSendJobVo> speedGroupSendJobVoList = speedGroupSendJobMapper.getSpeedGroupSendJobList(speedGroupSendJobQuery);

        if (speedGroupSendJobVoList != null && !speedGroupSendJobVoList.isEmpty()) {
            speedGroupSendJobVoList.forEach(it -> {
                //获取关联的机器人ID
                SpeedGroupSendJobDeviceQuery speedGroupSendJobDeviceQuery = new SpeedGroupSendJobDeviceQuery();
                speedGroupSendJobDeviceQuery.setMerId(it.getMerId());
                speedGroupSendJobDeviceQuery.setJobId(it.getId());
                List<SpeedGroupSendJobDeviceVo> speedGroupSendJobDeviceVoList = speedGroupSendJobDeviceMapper.getGroupSendJobDeviceList(speedGroupSendJobDeviceQuery);

                if (speedGroupSendJobDeviceVoList != null && !speedGroupSendJobDeviceVoList.isEmpty()) {
                    List<Long> deviceUniqueIds = speedGroupSendJobDeviceVoList.stream().map(SpeedGroupSendJobDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
                    //获取关联机器人的昵称
                    WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
                    wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                    wwDeviceQuery.setMerId(it.getMerId());
                    List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                    if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
                        List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                        it.setDeviceNames(deviceNames);
                    }
                }
                //无法发送的会员内部账号列表
                if (!StringUtils.isBlank(it.getExternalUserids())) {

                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        List<String> externalUserIdList = objectMapper.readValue(it.getExternalUserids(), new TypeReference<List<String>>() {
                        });
                        CustomerQuery customerQuery = new CustomerQuery();
                        customerQuery.setMerId(it.getMerId());
                        customerQuery.setExternalUserIdList(externalUserIdList);
                        List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
                        if (wwCustomerVoList != null && !wwCustomerVoList.isEmpty()) {
                            it.setUnSendWwCustomerVoList(wwCustomerVoList);
                        }
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }


        //获取确认人
        speedGroupSendJobVoList.forEach(it -> {
            if (it.getConfirmUserId() != null && it.getConfirmUserType() == 0) {
                BaseDto baseDto = new BaseDto();
                baseDto.setMerId(it.getConfirmUserId());
                Merchant merchant = userService.getById(baseDto);
                if (merchant != null) {
                    it.setConfirmUserName(merchant.getUserName());
                }
            }
            if (it.getConfirmUserId() != null && it.getConfirmUserType() == 1) {
                ChildMerchatDto childMerchatDto = new ChildMerchatDto();
                childMerchatDto.setMerId(it.getMerId());
                childMerchatDto.setId(it.getConfirmUserId());
                MerchatChild merchatChild = childMerchatService.getById(childMerchatDto);
                if (merchatChild != null) {
                    it.setConfirmUserName(merchatChild.getUserName());
                }
            }
        });

        return new MyPageInfo<>(speedGroupSendJobVoList);
    }

    @Override
    public Object getSpeedGroupSendJobDetail(SpeedGroupSendJobDto speedGroupSendJobDto) {
        if (speedGroupSendJobDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (speedGroupSendJobDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        SpeedGroupSendJob speedGroupSendJob = speedGroupSendJobMapper.getById(speedGroupSendJobDto.getId(), speedGroupSendJobDto.getMerId());

        if (speedGroupSendJob == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "极速群发任务不存在");
        }

        SpeedGroupSendJobVo speedGroupSendJobVo = new SpeedGroupSendJobVo();
        BeanUtil.copyProperties(speedGroupSendJob, speedGroupSendJobVo);

        //获取关联的机器人ID
        SpeedGroupSendJobDeviceQuery speedGroupSendJobDeviceQuery = new SpeedGroupSendJobDeviceQuery();
        speedGroupSendJobDeviceQuery.setMerId(speedGroupSendJobVo.getMerId());
        speedGroupSendJobDeviceQuery.setJobId(speedGroupSendJobVo.getId());
        List<SpeedGroupSendJobDeviceVo> speedGroupSendJobDeviceVoList = speedGroupSendJobDeviceMapper.getGroupSendJobDeviceList(speedGroupSendJobDeviceQuery);

        if (speedGroupSendJobDeviceVoList != null && !speedGroupSendJobDeviceVoList.isEmpty()) {
            List<Long> deviceUniqueIds = speedGroupSendJobDeviceVoList.stream().map(SpeedGroupSendJobDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
            //获取关联机器人的昵称
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
            wwDeviceQuery.setMerId(speedGroupSendJobVo.getMerId());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
                speedGroupSendJobVo.setWwDeviceVoList(wwDeviceList);
                List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                speedGroupSendJobVo.setDeviceNames(deviceNames);
            }
        }

        SpeedGroupSendTask speedGroupSendTask = speedGroupSendTaskMapper.getById(speedGroupSendJob.getTaskId(), speedGroupSendJob.getMerId());
        if (speedGroupSendTask != null) {
            //发给对象wxid（私聊就是客户wxid,群聊就是群wxid）
            List<String> sendWxids = new ArrayList<>();
            SpeedGroupSendTaskCustomerQuery speedGroupSendTaskCustomerQuery = new SpeedGroupSendTaskCustomerQuery();
            speedGroupSendTaskCustomerQuery.setMerId(speedGroupSendTask.getMerId());
            speedGroupSendTaskCustomerQuery.setTaskId(speedGroupSendTask.getId());
            List<SpeedGroupSendTaskCustomerVo> speedGroupSendTaskCustomerVoList = speedGroupSendTaskCustomerMapper.getSpendGroupSendTaskCustomerList(speedGroupSendTaskCustomerQuery);
            if (speedGroupSendTaskCustomerVoList != null && !speedGroupSendTaskCustomerVoList.isEmpty()) {

                for (SpeedGroupSendTaskCustomerVo speedGroupSendTaskCustomerVo : speedGroupSendTaskCustomerVoList) {
                    if (speedGroupSendTask.getCustomerType() != null && speedGroupSendTask.getCustomerType().equals(2)) {
                        List<WwCustomerVo> wwCustomerVoList = new ArrayList<>();
                        CustomerQuery customerQuery = new CustomerQuery();
                        customerQuery.setMerId(speedGroupSendTask.getMerId());
                        customerQuery.setWxids(sendWxids);
                        WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(speedGroupSendTaskCustomerVo.getSendWxid(), speedGroupSendTaskCustomerVo.getDeviceUniqueId(), speedGroupSendTaskCustomerVo.getMerId());
                        if (wwCustomer != null) {
                            WwCustomerVo wwCustomerVo = new WwCustomerVo();
                            BeanUtil.copyProperties(wwCustomer, wwCustomerVo);
                            WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), wwCustomer.getMerId());
                            if (wwDevice != null) {
                                wwCustomerVo.setDeviceName(wwDevice.getDeviceName());
                                wwCustomerVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                            }
                            wwCustomerVoList.add(wwCustomerVo);
                        }
                        speedGroupSendJobVo.setWwCustomerVoList(wwCustomerVoList);
                    }

                    if (speedGroupSendTask.getGroupType() != null && speedGroupSendTask.getGroupType().equals(2)) {
                        List<WwGroupVo> wwGroupList = new ArrayList<>();
                        WwGroup wwGroup = wwGroupMapper.selectByGroupWxId(speedGroupSendTaskCustomerVo.getMerId(), speedGroupSendTaskCustomerVo.getDeviceUniqueId(), speedGroupSendTaskCustomerVo.getSendWxid());
                        if (wwGroup != null) {
                            WwGroupVo wwGroupVo = new WwGroupVo();
                            BeanUtil.copyProperties(wwGroup, wwGroupVo);
                            WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), wwGroup.getMerId());
                            if (wwDevice != null) {
                                wwGroupVo.setDeviceName(wwDevice.getDeviceName());
                                wwGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                            }
                            wwGroupList.add(wwGroupVo);
                        }
                        speedGroupSendJobVo.setWwGroupVoList(wwGroupList);
                    }
                }
            }

        }
        return speedGroupSendJobVo;
    }


    @Override
    public void cancelSpeedGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if (batchGroupSendJobDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchGroupSendJobDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        SpeedGroupSendJob speedGroupSendJob = speedGroupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());

        if (speedGroupSendJob == null || (speedGroupSendJob.getStatus() != null && speedGroupSendJob.getStatus().equals(4))) {
            return;
        }
        speedGroupSendJob.setStatus(4);
        speedGroupSendJobMapper.update(speedGroupSendJob);

        if (!StringUtils.isBlank(speedGroupSendJob.getMsgId())) {
            WwCorp wwCorp = wwCorpMapper.getByCorpId(speedGroupSendJob.getCorpId(), speedGroupSendJob.getMerId());
            if (wwCorp == null) {
                return;
            }
            CorpApplication corpApplication = corpApplicationService.getByCorpId(wwCorp.getCorpId());
            if (Objects.isNull(corpApplication) || org.apache.commons.lang3.StringUtils.isAnyBlank(corpApplication.getAuthCorpId(), corpApplication.getPermanentCode())) {
                logger.error("企业应用授权信息错误, 取消极速群发被忽略");
                return;
            }

            String accessToken = WwApiUtil.getAppAccessToken(corpApplication.getAuthCorpId(), corpApplication.getPermanentCode());

            ObjectMapper mapper = new ObjectMapper();
            try {
                List<String> msgIds = mapper.readValue(speedGroupSendJob.getMsgId(), new TypeReference<List<String>>() {
                });
                if (msgIds != null && !msgIds.isEmpty()) {
                    for (String msgId : msgIds) {
                        WwApiUtil.stopBulkSending(accessToken, msgId);
                    }
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delSpeedGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if (batchGroupSendJobDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchGroupSendJobDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        SpeedGroupSendJob speedGroupSendJob = speedGroupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());

        if (speedGroupSendJob == null) {
            return;
        }

        SpeedGroupSendJobDeviceQuery speedGroupSendJobDeviceQuery = new SpeedGroupSendJobDeviceQuery();
        speedGroupSendJobDeviceQuery.setMerId(speedGroupSendJob.getMerId());
        speedGroupSendJobDeviceQuery.setJobId(speedGroupSendJob.getId());
        List<SpeedGroupSendJobDeviceVo> speedGroupSendJobDeviceVoList = speedGroupSendJobDeviceMapper.getGroupSendJobDeviceList(speedGroupSendJobDeviceQuery);
        if (speedGroupSendJobDeviceVoList != null && !speedGroupSendJobDeviceVoList.isEmpty()) {
            speedGroupSendJobDeviceVoList.forEach(it -> speedGroupSendJobDeviceMapper.delById(it.getId(), it.getMerId()));
        }

        speedGroupSendJobMapper.delById(speedGroupSendJob.getId(), speedGroupSendJob.getMerId());
    }

    @Override
    public void confirmSpeedGroupSendJob(BatchGroupSendJobDto batchGroupSendJobDto) {
        if (batchGroupSendJobDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchGroupSendJobDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        SpeedGroupSendJob speedGroupSendJob = speedGroupSendJobMapper.getById(batchGroupSendJobDto.getId(), batchGroupSendJobDto.getMerId());

        if (speedGroupSendJob == null || (speedGroupSendJob.getStatus() != null && speedGroupSendJob.getStatus().equals(1))) {
            return;
        }
        speedGroupSendJob.setStatus(2);
        if (batchGroupSendJobDto.getOperatorType() == 0) {
            speedGroupSendJob.setConfirmUserId(batchGroupSendJobDto.getMerId());
            speedGroupSendJob.setConfirmUserType(0);
        }
        if (batchGroupSendJobDto.getOperatorType() == 1) {
            speedGroupSendJob.setConfirmUserId(batchGroupSendJobDto.getChildId());
            speedGroupSendJob.setConfirmUserType(1);
        }
        speedGroupSendJobMapper.update(speedGroupSendJob);
    }

    @Override
    @Async("taskExecutor")
    public void autoGroupSendTaskSyncByImmediately(BaseDto baseDto) {
        logger.info("-----处理立即或者定时发送的极速群发任务----merId=" + baseDto.getMerId());
        int now = DateUtil.getTime();

        SpeedGroupSendTaskQuery speedGroupSendTaskQuery = new SpeedGroupSendTaskQuery();
        Long idStart = 0L;
        speedGroupSendTaskQuery.setMerId(baseDto.getMerId());
        speedGroupSendTaskQuery.setTypeList(com.google.common.collect.Lists.newArrayList(0, 1)); //立即和定时任务
        speedGroupSendTaskQuery.setSendTimeEnd(now + 60);     //查询所有一分钟之内将要进行中的任务
        speedGroupSendTaskQuery.setStatus(1); //进行中
        speedGroupSendTaskQuery.setAsc(true);
        speedGroupSendTaskQuery.setCurrent(1);
        speedGroupSendTaskQuery.setSize(50);
        speedGroupSendTaskQuery.setOrderByField("id");
        speedGroupSendTaskQuery.setIdStart(idStart);

        String orderBy = OrderByUtil.getOrderBy(speedGroupSendTaskQuery.getOrderByField(), speedGroupSendTaskQuery.isAsc());
        PageHelper.startPage(speedGroupSendTaskQuery.getCurrent(), speedGroupSendTaskQuery.getSize(), orderBy);
        List<SpeedGroupSendTaskVo> speedGroupSendTaskVoList = speedGroupSendTaskMapper.getSpeedGroupSendTaskList(speedGroupSendTaskQuery);

        while (speedGroupSendTaskVoList != null && !speedGroupSendTaskVoList.isEmpty()) {
            for (SpeedGroupSendTaskVo speedGroupSendTaskVo : speedGroupSendTaskVoList) {
                try {
                    if (speedGroupSendTaskVo.getId().longValue() > idStart.longValue()) {
                        idStart = speedGroupSendTaskVo.getId();
                    }
                    //处理群发任务
                    SpeedGroupSendTask speedGroupSendTask = new SpeedGroupSendTask();
                    BeanUtil.copyProperties(speedGroupSendTaskVo, speedGroupSendTask);
                    speedGroupSendTask.setHanderTime(speedGroupSendTask.getSendTime());
                    addGroupSendJob(speedGroupSendTask);

                    //处理完成，修改已完成
                    speedGroupSendTask.setUpdateTime(DateUtil.getTime());
                    speedGroupSendTask.setStatus(0); //已完成
                    speedGroupSendTaskMapper.update(speedGroupSendTask);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            speedGroupSendTaskQuery.setIdStart(idStart);
            PageHelper.startPage(speedGroupSendTaskQuery.getCurrent(), speedGroupSendTaskQuery.getSize(), orderBy);
            speedGroupSendTaskVoList = speedGroupSendTaskMapper.getSpeedGroupSendTaskList(speedGroupSendTaskQuery);
        }
    }

    @Override
    @Async("taskExecutor")
    public void autoGroupSendTaskSyncByCycle(BaseDto baseDto) {
        logger.info("-----处理循环的极速群发任务----merId=" + baseDto.getMerId());

        int now = DateUtil.getTime();

        SpeedGroupSendTaskQuery speedGroupSendTaskQuery = new SpeedGroupSendTaskQuery();
        Long idStart = 0L;
        speedGroupSendTaskQuery.setMerId(baseDto.getMerId());
        speedGroupSendTaskQuery.setTypeList(Lists.newArrayList(2, 3, 4)); //按时、按周、按日
        speedGroupSendTaskQuery.setStatus(1); //进行中
        speedGroupSendTaskQuery.setAsc(true);
        speedGroupSendTaskQuery.setCurrent(1);
        speedGroupSendTaskQuery.setSize(50);
        speedGroupSendTaskQuery.setOrderByField("id");
        speedGroupSendTaskQuery.setIdStart(idStart);

        String orderBy = OrderByUtil.getOrderBy(speedGroupSendTaskQuery.getOrderByField(), speedGroupSendTaskQuery.isAsc());
        PageHelper.startPage(speedGroupSendTaskQuery.getCurrent(), speedGroupSendTaskQuery.getSize(), orderBy);
        List<SpeedGroupSendTaskVo> speedGroupSendTaskVoList = speedGroupSendTaskMapper.getSpeedGroupSendTaskList(speedGroupSendTaskQuery);

        while (speedGroupSendTaskVoList != null && !speedGroupSendTaskVoList.isEmpty()) {
            for (SpeedGroupSendTaskVo speedGroupSendTaskVo : speedGroupSendTaskVoList) {
                try {
                    if (speedGroupSendTaskVo.getId().longValue() > idStart.longValue()) {
                        idStart = speedGroupSendTaskVo.getId();
                    }

                    SpeedGroupSendTask speedGroupSendTask = new SpeedGroupSendTask();
                    BeanUtil.copyProperties(speedGroupSendTaskVo, speedGroupSendTask);


                    //截止状态(0-不截止；1-截止)
                    Integer deadStatus = Tools.getInteger(speedGroupSendTask.getDeadStatus());
                    if (deadStatus.intValue() == 1) { //如果是截止状态，则需要验证截止时间是否到期
                        //获取截止时间
                        Integer deadTime = Tools.getInteger(speedGroupSendTask.getDeadTime());
                        //截止时间比当前时间小，则表示已经到期了，将此任务自动关闭
                        if (deadTime < now) {
                            speedGroupSendTask.setStatus(0); //已关闭
                            speedGroupSendTask.setUpdateTime(now);
                            speedGroupSendTask.setHanderTime(now);
                            speedGroupSendTaskMapper.update(speedGroupSendTask);
                            continue;
                        }
                    }

                    //判断今天是否已经发送,根据发送时间来判断
                    if (speedGroupSendTask.getHanderTime() != null) { //已经处理过该任务，则需要判断当天是否已经处理过
                        Date sendTime_date = new Date(speedGroupSendTask.getHanderTime() * 1000L);
                        LocalDate localDate = sendTime_date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        //发送时间和当前时间一样，表示当天已经处理过，不发送了
                        if (localDate.isEqual(LocalDate.now())) {
                            continue;
                        }
                    }

                    boolean result = verifyTime(speedGroupSendTask);
                    if (!result) {
                        continue;
                    }


                    //处理群发任务
                    //这次发送时间,当天日期+设置的发送时间
                    String sendTimeNewStr = DateUtil.today() + " " + speedGroupSendTask.getTime() + ":00";
                    int sendTimeNew = (int) (DateUtil.parse(sendTimeNewStr, "yyyy-MM-dd HH:mm:ss").getTime() / 1000L);
                    speedGroupSendTask.setHanderTime(sendTimeNew);
                    addGroupSendJob(speedGroupSendTask);

                    //处理完成，修改已完成
                    speedGroupSendTask.setUpdateTime(DateUtil.getTime());
                    speedGroupSendTaskMapper.update(speedGroupSendTask);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            speedGroupSendTaskQuery.setIdStart(idStart);
            PageHelper.startPage(speedGroupSendTaskQuery.getCurrent(), speedGroupSendTaskQuery.getSize(), orderBy);
            speedGroupSendTaskVoList = speedGroupSendTaskMapper.getSpeedGroupSendTaskList(speedGroupSendTaskQuery);
        }

    }


    @Override
    @Async("taskExecutor")
    public void autoGroupSendJob(BaseDto baseDto) {
        logger.info("-----处理的极速群发的job----merId=" + baseDto.getMerId());

        int now = DateUtil.getTime();

        SpeedGroupSendJobQuery speedGroupSendJobQuery = new SpeedGroupSendJobQuery();
        Long idStart = 0L;
        speedGroupSendJobQuery.setMerId(baseDto.getMerId());
        speedGroupSendJobQuery.setStatus(1); //进行中
        speedGroupSendJobQuery.setStartSendTimeEnd(now);
        speedGroupSendJobQuery.setAsc(true);
        speedGroupSendJobQuery.setCurrent(1);
        speedGroupSendJobQuery.setSize(50);
        speedGroupSendJobQuery.setOrderByField("id");
        speedGroupSendJobQuery.setIdStart(idStart);

        String orderBy = OrderByUtil.getOrderBy(speedGroupSendJobQuery.getOrderByField(), speedGroupSendJobQuery.isAsc());
        PageHelper.startPage(speedGroupSendJobQuery.getCurrent(), speedGroupSendJobQuery.getSize(), orderBy);
        List<SpeedGroupSendJobVo> speedGroupSendJobList = speedGroupSendJobMapper.getSpeedGroupSendJobList(speedGroupSendJobQuery);

        while (speedGroupSendJobList != null && !speedGroupSendJobList.isEmpty()) {
            for (SpeedGroupSendJobVo speedGroupSendJobVo : speedGroupSendJobList) {
                List<String> msgIds = new ArrayList<>();
                try {
                    if (speedGroupSendJobVo.getId().longValue() > idStart.longValue()) {
                        idStart = speedGroupSendJobVo.getId();
                    }
                    //筛选发送对象
                    List<WwCustomerVo> wwCustomerVoList = filterSendTarget(speedGroupSendJobVo);
                    if (wwCustomerVoList != null && !wwCustomerVoList.isEmpty()) {
                        List<String> allExternalUserids = wwCustomerVoList.stream().map(WwCustomerVo::getExternalUserid).filter(Objects::nonNull).distinct().collect(Collectors.toList());
                        if (!allExternalUserids.isEmpty()) {
                            List<List<String>> splitExternalUserids = new ArrayList<>();
                            int batchSize = 10000;
                            for (int i = 0; i < allExternalUserids.size(); i += batchSize) {
                                splitExternalUserids.add(allExternalUserids.subList(i, Math.min(i + batchSize, allExternalUserids.size())));
                            }

                            for (List<String> externalUserids : splitExternalUserids) {
                                if (externalUserids != null && !externalUserids.isEmpty()) {
                                    String msgId = createBulkSending(externalUserids, speedGroupSendJobVo);
                                    msgIds.add(msgId);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("处理极速群发任务失败: {}", speedGroupSendJobVo.getId());
                    logger.error(e.getMessage(), e);
                } finally {
                    SpeedGroupSendJob speedGroupSendJob = new SpeedGroupSendJob();
                    speedGroupSendJob.setId(speedGroupSendJobVo.getId());
                    speedGroupSendJob.setStatus(2);
                    if (!msgIds.isEmpty()) {
                        speedGroupSendJob.setMsgId(JSONObject.toJSONString(msgIds));
                    }
                    speedGroupSendJobMapper.updateStatus(speedGroupSendJob);
                }
            }
            speedGroupSendJobQuery.setIdStart(idStart);
            PageHelper.startPage(speedGroupSendJobQuery.getCurrent(), speedGroupSendJobQuery.getSize(), orderBy);
            speedGroupSendJobList = speedGroupSendJobMapper.getSpeedGroupSendJobList(speedGroupSendJobQuery);
        }

    }


    public String createBulkSending(List<String> externalUserids, SpeedGroupSendJobVo speedGroupSendJobVo) {
        WwCorp wwCorp = wwCorpMapper.getByCorpId(speedGroupSendJobVo.getCorpId(), speedGroupSendJobVo.getMerId());
        if (wwCorp == null) {
            return null;
        }

        /*String accessToken = (String) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.QYWX_TOKEN.getKey(), wwCorp.getEntId()));
        if (StringUtils.isBlank(accessToken)) {
            accessToken = WwApiUtil.getAccessToken(wwCorp.getEntId(), wwCorp.getEntSecret());
//            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.QYWX_TOKEN.getKey(), wwCorp.getEntId()), accessToken);
        }*/
        String dataSourceKey = DynamicDataSourceContextHolder.getDataSourceKey();

        CorpApplication corpApplication = corpApplicationService.getByCorpId(wwCorp.getCorpId());
        if (Objects.isNull(corpApplication)) {
            throw new BusinessException("当前企业未进行应用授权");
        }

        DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey);

        String accessToken = WwApiUtil.getAppAccessToken(corpApplication.getAuthCorpId(), corpApplication.getPermanentCode());
        WwCreateBulkSendDTO wwCreateBulkSendDTO = new WwCreateBulkSendDTO();
        wwCreateBulkSendDTO.setExternal_userid(externalUserids);
        if (StringUtils.isBlank(speedGroupSendJobVo.getMsgDatas())) {
            return null;
        }
        List<WwCreateBulkSendDTO.AttachmentItem> attachments = new ArrayList<>();
        List<MsgData> msgDataList = JSONObject.parseArray(speedGroupSendJobVo.getMsgDatas(), MsgData.class);
        for (MsgData msgData : msgDataList) {
            try {
                //文本
                if (msgData.getMsgType() == 1) {
                    WwCreateBulkSendDTO.TextContent textContent = new WwCreateBulkSendDTO.TextContent();
                    textContent.setContent(msgData.getContent());
                    wwCreateBulkSendDTO.setText(textContent);
                }
                //图片
                if (msgData.getMsgType() == 2) {
                    String mediaId = WwApiUtil.uploadTempMedia(accessToken, msgData.getImgUrl(), "image");
                    WwCreateBulkSendDTO.AttachmentItem attachmentItem = new WwCreateBulkSendDTO.AttachmentItem();
                    WwCreateBulkSendDTO.Image image = new WwCreateBulkSendDTO.Image();
                    image.setMedia_id(mediaId);
                    attachmentItem.setImage(image);
                    attachmentItem.setMsgtype("image");
                    attachments.add(attachmentItem);
                }
                //视屏
                if (msgData.getMsgType() == 4) {
                    String mediaId = WwApiUtil.uploadTempMedia(accessToken, msgData.getVideoUrl(), "video");
                    WwCreateBulkSendDTO.AttachmentItem attachmentItem = new WwCreateBulkSendDTO.AttachmentItem();
                    WwCreateBulkSendDTO.Media media = new WwCreateBulkSendDTO.Media();
                    media.setMedia_id(mediaId);
                    attachmentItem.setVideo(media);
                    attachmentItem.setMsgtype("video");
                    attachments.add(attachmentItem);
                }
                //文件
                if (msgData.getMsgType() == 8) {
                    String mediaId = WwApiUtil.uploadTempMedia(accessToken, msgData.getFileUrl(), "file");
                    WwCreateBulkSendDTO.AttachmentItem attachmentItem = new WwCreateBulkSendDTO.AttachmentItem();
                    WwCreateBulkSendDTO.Media media = new WwCreateBulkSendDTO.Media();
                    media.setMedia_id(mediaId);
                    attachmentItem.setFile(media);
                    attachmentItem.setMsgtype("file");
                    attachments.add(attachmentItem);
                }
                //链接
                if (msgData.getMsgType() == 6) {
                    WwCreateBulkSendDTO.AttachmentItem attachmentItem = new WwCreateBulkSendDTO.AttachmentItem();
                    WwCreateBulkSendDTO.Link link = new WwCreateBulkSendDTO.Link();
                    link.setTitle(msgData.getLinkTitle());
                    link.setDesc(msgData.getLinkDesc());
                    link.setUrl(msgData.getLinkUrl());
                    link.setPicurl(msgData.getLinkImageUrl());
                    attachmentItem.setLink(link);
                    attachmentItem.setMsgtype("link");
                    attachments.add(attachmentItem);
                }
                //小程序
                if (msgData.getMsgType() == 13) {
                    String mediaId = WwApiUtil.uploadTempMedia(accessToken, msgData.getMiniImgUrl(), "miniprogram");
                    WwCreateBulkSendDTO.AttachmentItem attachmentItem = new WwCreateBulkSendDTO.AttachmentItem();
                    WwCreateBulkSendDTO.Miniprogram miniprogram = new WwCreateBulkSendDTO.Miniprogram();
                    miniprogram.setAppid(msgData.getMiniProAppId());
                    miniprogram.setTitle(msgData.getMiniProTitle());
                    miniprogram.setPic_media_id(mediaId);
                    miniprogram.setPage(msgData.getMiniProUrl());
                    attachmentItem.setMiniprogram(miniprogram);
                    attachmentItem.setMsgtype("miniprogram");
                    attachments.add(attachmentItem);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (!attachments.isEmpty()) {
            wwCreateBulkSendDTO.setAttachments(attachments);
        }


        if (wwCreateBulkSendDTO.getText() == null && (wwCreateBulkSendDTO.getAttachments() == null || wwCreateBulkSendDTO.getAttachments().isEmpty())) {
            return null;
        }

        logger.info("wwCreateBulkSendDTO is {}", wwCreateBulkSendDTO);

        WwCreateBulkSendResultDTO wwCreateBulkSendResultDTO = WwApiUtil.createBulkSending(accessToken, wwCreateBulkSendDTO);
        if (wwCreateBulkSendResultDTO != null && wwCreateBulkSendResultDTO.getFail_list() != null && !wwCreateBulkSendResultDTO.getFail_list().isEmpty()) {

            SpeedGroupSendJob speedGroupSendJob = speedGroupSendJobMapper.getById(speedGroupSendJobVo.getId(), speedGroupSendJobVo.getMerId());
            if (speedGroupSendJob != null) {
                if (StringUtils.isBlank(speedGroupSendJob.getExternalUserids())) {
                    speedGroupSendJob.setExternalUserids(JSONObject.toJSONString(wwCreateBulkSendResultDTO.getFail_list()));
                } else {
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        List<String> externalUseridList = mapper.readValue(speedGroupSendJob.getExternalUserids(), new TypeReference<List<String>>() {
                        });
                        externalUseridList.addAll(wwCreateBulkSendResultDTO.getFail_list());
                        speedGroupSendJob.setExternalUserids(JSONObject.toJSONString(externalUseridList));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
                speedGroupSendJob.setId(speedGroupSendJobVo.getId());
                speedGroupSendJobMapper.updateExternalUserids(speedGroupSendJob);
            }

        }
        if (wwCreateBulkSendResultDTO != null && !StringUtils.isBlank(wwCreateBulkSendResultDTO.getMsgid())) {
            return wwCreateBulkSendResultDTO.getMsgid();
        }
        return null;
    }

    public List<WwCustomerVo> filterSendTarget(SpeedGroupSendJobVo speedGroupSendJobVo) {
        List<WwCustomerVo> customerVos = new ArrayList<>();
        Integer customerSwitch = Tools.getInteger(speedGroupSendJobVo.getCustomerSwitch());
        if (customerSwitch != null && customerSwitch == 1) {

            //筛选类型(0-全部客户；1-筛选客户；2-选择客户)
            Integer customerType = Tools.getInteger(speedGroupSendJobVo.getCustomerType());
            if (customerType.intValue() == 0 || customerType.intValue() == 1) {

                SpeedGroupSendJobDeviceQuery speedGroupSendJobDeviceQuery = new SpeedGroupSendJobDeviceQuery();
                speedGroupSendJobDeviceQuery.setMerId(speedGroupSendJobVo.getMerId());
                speedGroupSendJobDeviceQuery.setJobId(speedGroupSendJobVo.getId());
                List<SpeedGroupSendJobDeviceVo> speedGroupSendJobDeviceVoList = speedGroupSendJobDeviceMapper.getGroupSendJobDeviceList(speedGroupSendJobDeviceQuery);
                if (speedGroupSendJobDeviceVoList == null) {
                    return null;
                }
                List<Long> deviceUniqueIds = speedGroupSendJobDeviceVoList.stream().map(SpeedGroupSendJobDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
                //需要遍历客户表
                //查询所有的客户
                CustomerQuery customerQuery = new CustomerQuery();
                customerQuery.setMerId(speedGroupSendJobVo.getMerId());
                customerQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
                Long idStart = 0L;
                customerQuery.setAsc(true);
                customerQuery.setCurrent(1);
                customerQuery.setSize(50);
                customerQuery.setOrderByField("id");
                customerQuery.setIdStart(idStart);

                String orderBy = OrderByUtil.getOrderBy(customerQuery.getOrderByField(), customerQuery.isAsc());
                PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
                List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
                while (wwCustomerVoList != null && wwCustomerVoList.size() > 0) {
                    for (WwCustomerVo wwCustomerVo : wwCustomerVoList) {
                        try {
                            if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                                idStart = wwCustomerVo.getId();
                            }
                            //验证客户是否有内部会员内部账号
                            if (StringUtils.isBlank(wwCustomerVo.getExternalUserid())) {
                                continue;
                            }
                            //客户验证结果，默认为通过验证
                            boolean result = true;
                            if (customerType.intValue() == 1) { //按照条件筛选客户，需要验证
                                result = verifyCustomer(speedGroupSendJobVo, wwCustomerVo);
                                //勾选了排除条件
                                if (result && speedGroupSendJobVo.getCustomerExcludeCondition() != null && speedGroupSendJobVo.getCustomerExcludeCondition() == 1) {
                                    boolean ifExclude = excludeCustomer(speedGroupSendJobVo, wwCustomerVo);
                                    if (ifExclude) {
                                        continue;
                                    }
                                } else if (result && Objects.equals(speedGroupSendJobVo.getCustomerExcludeNewUserOpt(), 1)) {
                                    boolean ifExclude = excludeCustomerV1(speedGroupSendJobVo, wwCustomerVo);
                                    if (ifExclude) {
                                        continue;
                                    }
                                }
                            }
                            if (result) {//符合条件，则添加消息
                                customerVos.add(wwCustomerVo);
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                    customerQuery.setIdStart(idStart);
                    PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
                    wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
                }
            } else if (customerType.intValue() == 2) { //选择客户
                //查询选择的客户
                SpeedGroupSendTaskCustomerQuery speedGroupSendTaskCustomerQuery = new SpeedGroupSendTaskCustomerQuery();
                speedGroupSendTaskCustomerQuery.setMerId(speedGroupSendJobVo.getMerId());
                speedGroupSendTaskCustomerQuery.setType(0); //类型（0-私聊;1-群聊）
                speedGroupSendTaskCustomerQuery.setTaskId(speedGroupSendJobVo.getTaskId());

                Long idStart = 0L;
                speedGroupSendTaskCustomerQuery.setAsc(true);
                speedGroupSendTaskCustomerQuery.setCurrent(1);
                speedGroupSendTaskCustomerQuery.setSize(50);
                speedGroupSendTaskCustomerQuery.setOrderByField("id");
                speedGroupSendTaskCustomerQuery.setIdStart(idStart);
                String orderBy = OrderByUtil.getOrderBy(speedGroupSendTaskCustomerQuery.getOrderByField(), speedGroupSendTaskCustomerQuery.isAsc());
                PageHelper.startPage(speedGroupSendTaskCustomerQuery.getCurrent(), speedGroupSendTaskCustomerQuery.getSize(), orderBy);
                List<SpeedGroupSendTaskCustomerVo> speedGroupSendTaskCustomerVoList = speedGroupSendTaskCustomerMapper.getSpendGroupSendTaskCustomerList(speedGroupSendTaskCustomerQuery);
                while (speedGroupSendTaskCustomerVoList != null && speedGroupSendTaskCustomerVoList.size() > 0) {
                    for (SpeedGroupSendTaskCustomerVo speedGroupSendTaskCustomerVo : speedGroupSendTaskCustomerVoList) {
                        try {
                            if (speedGroupSendTaskCustomerVo.getId().longValue() > idStart.longValue()) {
                                idStart = speedGroupSendTaskCustomerVo.getId();
                            }

                            //默认黑名单不通过
                            WwCustomerBlacklist wwCustomerBlacklist = blackListMapper.selectByWxid(speedGroupSendTaskCustomerVo.getMerId(), speedGroupSendTaskCustomerVo.getSendWxid());
                            if (wwCustomerBlacklist != null) { //在黑名单中
                                logger.info("黑名单会员wxid={}, merId={}", speedGroupSendTaskCustomerVo.getSendWxid(), speedGroupSendTaskCustomerVo.getMerId());
                                continue;
                            }

                            WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(speedGroupSendTaskCustomerVo.getSendWxid(), speedGroupSendTaskCustomerVo.getDeviceUniqueId(), speedGroupSendTaskCustomerVo.getMerId());
                            if (wwCustomer != null) {

                                //验证客户是否有内部会员内部账号
                                if (StringUtils.isBlank(wwCustomer.getExternalUserid())) {
                                    continue;
                                }
                                WwCustomerVo wwCustomerVo = new WwCustomerVo();
                                BeanUtil.copyProperties(wwCustomer, wwCustomerVo);
                                customerVos.add(wwCustomerVo);
                            }
                        } catch (Exception e) {
                            logger.error("--循环选择客户群发消息失败--error={}", e.getMessage(), e);
                        }
                    }
                    speedGroupSendTaskCustomerQuery.setIdStart(idStart);
                    PageHelper.startPage(speedGroupSendTaskCustomerQuery.getCurrent(), speedGroupSendTaskCustomerQuery.getSize(), orderBy);
                    speedGroupSendTaskCustomerVoList = speedGroupSendTaskCustomerMapper.getSpendGroupSendTaskCustomerList(speedGroupSendTaskCustomerQuery);
                }
            }
        }
        return customerVos;
    }


    public boolean verifyCustomer(SpeedGroupSendJobVo speedGroupSendJobVo, WwCustomerVo wwCustomerVo) {
        if (wwCustomerVo == null) {
            return false;
        }

        //是否开启群聊开关
        Integer customerSwitch = Tools.getInteger(speedGroupSendJobVo.getCustomerSwitch());
        if (customerSwitch.intValue() == 0) { //不开启客户消息，直接不通过
            return false;
        }

        //默认黑名单不通过
        WwCustomerBlacklist wwCustomerBlacklist = blackListMapper.selectByWxid(wwCustomerVo.getMerId(), wwCustomerVo.getWxid());
        if (wwCustomerBlacklist != null) { //在黑名单中
            logger.info("黑名单会员wxid={}, merId={}", wwCustomerVo.getWxid(), wwCustomerVo.getMerId());
            return false;
        }

        //客户类型(0-全部客户；1-部分客户)
        Integer customerType = Tools.getInteger(speedGroupSendJobVo.getCustomerType());
        if (customerType.intValue() == 1) { //部分客户，则需要验证条件

            //客户企业标签选项(0-含任意标签；1-含所有标签；2-未打任何标签)
            Integer customerEnterpriseTagOpt = speedGroupSendJobVo.getCustomerEnterpriseTagOpt();
            if (customerEnterpriseTagOpt != null) {
                //封装客户已打的标签
                List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.queryByCustomerId(wwCustomerVo.getId(), wwCustomerVo.getMerId());
                List<Long> wwCustomerTagedList = new ArrayList<>();
                if (wwCustomerTagsList != null && wwCustomerTagsList.size() > 0) {
                    for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                        wwCustomerTagedList.add(wwCustomerTags.getTagId());
                    }
                }

                //2-未打任何标签
                if (customerEnterpriseTagOpt.intValue() == 2) {
                    if (wwCustomerTagedList.size() > 0) {
                        return false;
                    }
                } else {
                    //标签列表
                    List<Long> customerEnterpriseTagList = JSONObject.parseArray(speedGroupSendJobVo.getCustomerEnterpriseTags(), Long.class);
                    if (customerEnterpriseTagList == null || customerEnterpriseTagList.size() == 0) { //没有找到，则不回复
                        return false;
                    }
                    if (customerEnterpriseTagOpt.intValue() == 0) { //满足任意一个
                        boolean tagFlag = false;
                        for (Long customerEnterpriseTag : customerEnterpriseTagList) {
                            if (wwCustomerTagedList.contains(customerEnterpriseTag)) {//找到一个符合的，就返回通过
                                tagFlag = true;
                                break;
                            }
                        }
                        if (!tagFlag) {
                            return false;
                        }
                    } else if (customerEnterpriseTagOpt.intValue() == 1) {//满足所有触发
                        if (!wwCustomerTagedList.containsAll(customerEnterpriseTagList)) {
                            return false;
                        }
                    }
                }
            }

            //加好友时间
            String customerCreateDayStart = speedGroupSendJobVo.getCustomerCreateDayStart();
            String customerCreateDayEnd = speedGroupSendJobVo.getCustomerCreateDayEnd();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(customerCreateDayStart) && org.apache.commons.lang3.StringUtils.isNotBlank(customerCreateDayEnd)) {
                Integer customerCreateTime = wwCustomerVo.getCreateTime();
                if (customerCreateTime == null) {//如果没有添加好友时间，则不通过
                    return false;
                }
                //判断旧发送时间是否在允许区间内
                Instant instant_groupCreateTime = Instant.ofEpochMilli(customerCreateTime * 1000L);
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
                boolean withinTimeInterval_customerCreateTime = Tools.isWithinDateInterval(localDateTime, LocalDate.parse(customerCreateDayStart), LocalDate.parse(customerCreateDayEnd));
                if (!withinTimeInterval_customerCreateTime) {
                    return false;
                }
            }

            //客户备注选项(0-无备注；1-有备注)
            Integer customerRemarkOpt = speedGroupSendJobVo.getCustomerRemarkOpt();
            if (customerRemarkOpt != null) {
                if (customerRemarkOpt.intValue() == 0) {//无备注
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(wwCustomerVo.getRemark())) {
                        return false;
                    }
                } else if (customerRemarkOpt.intValue() == 1) { //有备注
                    if (org.apache.commons.lang3.StringUtils.isBlank(wwCustomerVo.getRemark())) {
                        return false;
                    }
                }
            }

            //性别(0-未知；1-男；2-女)
            Integer customerGenders = speedGroupSendJobVo.getCustomerGenders();
            if (customerGenders != null) {
                //验证客户性别是否跟配置的符合
                if (customerGenders.intValue() != Tools.getInteger(wwCustomerVo.getGender()).intValue()) {
                    return false;
                }
            }
        }
        return true;
    }


    private boolean excludeCustomer(SpeedGroupSendJobVo speedGroupSendJobVo, WwCustomerVo wwCustomerVo) {

        //客户企业标签选项(0-含任意标签；1-含所有标签；2-未打任何标签)
        Integer customerExcludeEnterpriseTagOpt = speedGroupSendJobVo.getCustomerExcludeEnterpriseTagOpt();
        if (customerExcludeEnterpriseTagOpt != null) {
            //封装客户已打的标签
            List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.queryByCustomerId(wwCustomerVo.getId(), wwCustomerVo.getMerId());
            List<Long> wwCustomerTagedList = new ArrayList<>();
            if (wwCustomerTagsList != null && wwCustomerTagsList.size() > 0) {
                for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                    wwCustomerTagedList.add(wwCustomerTags.getTagId());
                }
            }

            //2-未打任何标签
            if (customerExcludeEnterpriseTagOpt.intValue() == 2) {
                if (wwCustomerTagedList.size() > 0) {
                    return false;
                }
            } else {
                //标签列表
                List<Long> customerEnterpriseTagList = JSONObject.parseArray(speedGroupSendJobVo.getCustomerExcludeEnterpriseTags(), Long.class);
                if (customerEnterpriseTagList == null || customerEnterpriseTagList.size() == 0) { //没有找到，则不回复
                    return false;
                }
                if (customerExcludeEnterpriseTagOpt.intValue() == 0) { //满足任意一个
                    boolean tagFlag = false;
                    for (Long customerEnterpriseTag : customerEnterpriseTagList) {
                        if (wwCustomerTagedList.contains(customerEnterpriseTag)) {//找到一个符合的，就返回通过
                            tagFlag = true;
                            break;
                        }
                    }
                    if (!tagFlag) {
                        return false;
                    }
                } else if (customerExcludeEnterpriseTagOpt.intValue() == 1) {//满足所有触发
                    if (!wwCustomerTagedList.containsAll(customerEnterpriseTagList)) {
                        return false;
                    }
                }
            }
        }

        //加好友时间
        String customerCreateDayStart = speedGroupSendJobVo.getCustomerExcludeCreateDayStart();
        String customerCreateDayEnd = speedGroupSendJobVo.getCustomerExcludeCreateDayEnd();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(customerCreateDayStart) && org.apache.commons.lang3.StringUtils.isNotBlank(customerCreateDayEnd)) {
            Integer customerCreateTime = wwCustomerVo.getCreateTime();
            if (customerCreateTime == null) {//如果没有添加好友时间，则不通过
                return false;
            }
            //判断旧发送时间是否在允许区间内
            Instant instant_groupCreateTime = Instant.ofEpochMilli(customerCreateTime * 1000L);
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
            boolean withinTimeInterval_customerCreateTime = Tools.isWithinDateInterval(localDateTime, LocalDate.parse(customerCreateDayStart), LocalDate.parse(customerCreateDayEnd));
            if (!withinTimeInterval_customerCreateTime) {
                return false;
            }
        }

        //当日添加时间
        if (Objects.equals(speedGroupSendJobVo.getCustomerExcludeNewUserOpt(), 1)) {
            //
            DateTime r = cn.hutool.core.date.DateUtil.date();
            int start = (int) (cn.hutool.core.date.DateUtil.beginOfDay(r).getTime() / 1000L);
            int end = (int) (cn.hutool.core.date.DateUtil.endOfDay(r).getTime() / 1000L);
            Integer customerCreateTime = wwCustomerVo.getCreateTime();
            //
            return customerCreateTime > start && customerCreateTime < end;
        }


        //客户备注选项(0-无备注；1-有备注)
        Integer customerRemarkOpt = speedGroupSendJobVo.getCustomerExcludeRemarkOpt();
        if (customerRemarkOpt != null) {
            if (customerRemarkOpt.intValue() == 0) {//无备注
                if (org.apache.commons.lang3.StringUtils.isNotBlank(wwCustomerVo.getRemark())) {
                    return false;
                }
            } else if (customerRemarkOpt.intValue() == 1) { //有备注
                if (org.apache.commons.lang3.StringUtils.isBlank(wwCustomerVo.getRemark())) {
                    return false;
                }
            }
        }

        //性别(0-未知；1-男；2-女)
        Integer customerGenders = speedGroupSendJobVo.getCustomerExcludeGenders();
        if (customerGenders != null) {
            //验证客户性别是否跟配置的符合
            if (customerGenders.intValue() != Tools.getInteger(wwCustomerVo.getGender()).intValue()) {
                return false;
            }
        }

        return true;
    }

    private boolean excludeCustomerV1(SpeedGroupSendJobVo speedGroupSendJobVo, WwCustomerVo wwCustomerVo) {

        //当日添加时间
        if (Objects.equals(speedGroupSendJobVo.getCustomerExcludeNewUserOpt(), 1)) {
            //
            DateTime r = cn.hutool.core.date.DateUtil.date();
            int start = (int) (cn.hutool.core.date.DateUtil.beginOfDay(r).getTime() / 1000L);
            int end = (int) (cn.hutool.core.date.DateUtil.endOfDay(r).getTime() / 1000L);
            Integer customerCreateTime = wwCustomerVo.getCreateTime();
            //
            return customerCreateTime > start && customerCreateTime < end;
        }
        return true;
    }


    @Override
    public void addGroupSendJob(SpeedGroupSendTask speedGroupSendTask) {
        if (speedGroupSendTask == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }


        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                try {
                    int now = DateUtil.getTime();

                    //新建群发消息
                    SpeedGroupSendJob speedGroupSendJob = new SpeedGroupSendJob();
                    speedGroupSendJob.setId(IdWorker.getId());
                    speedGroupSendJob.setMerId(speedGroupSendTask.getMerId());
                    speedGroupSendJob.setTaskId(speedGroupSendTask.getId());
                    speedGroupSendJob.setCorpId(speedGroupSendTask.getCorpId());
                    speedGroupSendJob.setName(speedGroupSendTask.getName());
                    speedGroupSendJob.setType(speedGroupSendTask.getType());
                    speedGroupSendJob.setSendTime(speedGroupSendTask.getSendTime());
                    speedGroupSendJob.setTime(speedGroupSendTask.getTime());
                    speedGroupSendJob.setWeek(speedGroupSendTask.getWeek());
                    speedGroupSendJob.setDay(speedGroupSendTask.getDay());
                    speedGroupSendJob.setCustomerSwitch(speedGroupSendTask.getCustomerSwitch());
                    speedGroupSendJob.setCustomerType(speedGroupSendTask.getCustomerType());
                    speedGroupSendJob.setCustomerEnterpriseTagOpt(speedGroupSendTask.getCustomerEnterpriseTagOpt());
                    speedGroupSendJob.setCustomerEnterpriseTags(speedGroupSendTask.getCustomerEnterpriseTags());
                    speedGroupSendJob.setCustomerCreateDayStart(speedGroupSendTask.getCustomerCreateDayStart());
                    speedGroupSendJob.setCustomerCreateDayEnd(speedGroupSendTask.getCustomerCreateDayEnd());
                    speedGroupSendJob.setCustomerRemarkOpt(speedGroupSendTask.getCustomerRemarkOpt());
                    speedGroupSendJob.setCustomerGenders(speedGroupSendTask.getCustomerGenders());
                    speedGroupSendJob.setCustomerExcludeCondition(speedGroupSendTask.getCustomerExcludeCondition());
                    speedGroupSendJob.setCustomerExcludeEnterpriseTagOpt(speedGroupSendTask.getCustomerExcludeEnterpriseTagOpt());
                    speedGroupSendJob.setCustomerExcludeEnterpriseTags(speedGroupSendTask.getCustomerExcludeEnterpriseTags());
                    speedGroupSendJob.setCustomerExcludeCreateDayStart(speedGroupSendTask.getCustomerExcludeCreateDayStart());
                    speedGroupSendJob.setCustomerExcludeCreateDayEnd(speedGroupSendTask.getCustomerExcludeCreateDayEnd());
                    speedGroupSendJob.setCustomerExcludeRemarkOpt(speedGroupSendTask.getCustomerExcludeRemarkOpt());
                    speedGroupSendJob.setCustomerExcludeGenders(speedGroupSendTask.getCustomerExcludeGenders());
                    speedGroupSendJob.setCustomerExcludeNewUserOpt(speedGroupSendTask.getCustomerExcludeNewUserOpt());
                    speedGroupSendJob.setGroupSwitch(speedGroupSendTask.getGroupSwitch());
                    speedGroupSendJob.setGroupType(speedGroupSendTask.getGroupType());
                    speedGroupSendJob.setGroupNameKeywordOpt(speedGroupSendTask.getGroupNameKeywordOpt());
                    speedGroupSendJob.setGroupNameKeywords(speedGroupSendTask.getGroupNameKeywords());
                    speedGroupSendJob.setGroupTagOpt(speedGroupSendTask.getGroupTagOpt());
                    speedGroupSendJob.setGroupTags(speedGroupSendTask.getGroupTags());
                    speedGroupSendJob.setGroupMemberIdentitys(speedGroupSendTask.getGroupMemberIdentitys());
                    speedGroupSendJob.setGroupMemberTotalMin(speedGroupSendTask.getGroupMemberTotalMin());
                    speedGroupSendJob.setGroupMemberTotalMax(speedGroupSendTask.getGroupMemberTotalMax());
                    speedGroupSendJob.setGroupCreateDayStart(speedGroupSendTask.getGroupCreateDayStart());
                    speedGroupSendJob.setGroupCreateDayEnd(speedGroupSendTask.getGroupCreateDayEnd());
                    speedGroupSendJob.setMsgType(speedGroupSendTask.getMsgType());
                    speedGroupSendJob.setNotice(speedGroupSendTask.getNotice());
                    speedGroupSendJob.setMsgDatas(speedGroupSendTask.getMsgDatas());
                    speedGroupSendJob.setStatus(speedGroupSendTask.getStatus());
                    speedGroupSendJob.setStartSendTime(speedGroupSendTask.getHanderTime());
                    speedGroupSendJob.setCreateTime(now);
                    speedGroupSendJob.setUpdateTime(now);
                    speedGroupSendJobMapper.insertSelective(speedGroupSendJob);

                    //添加机器人表
                    List<SpeedGroupSendTaskDevice> speedGroupSendTaskDeviceList = speedGroupSendTaskDeviceMapper.getByTaskId(speedGroupSendTask.getId(), speedGroupSendTask.getMerId());
                    if (speedGroupSendTaskDeviceList != null && speedGroupSendTaskDeviceList.size() > 0) {
                        for (SpeedGroupSendTaskDevice speedGroupSendTaskDevice : speedGroupSendTaskDeviceList) {
                            //查询该机器人存不存在
                            WwDevice wwDevice = wwDeviceMapper.getById(speedGroupSendTaskDevice.getDeviceUniqueId(), speedGroupSendTaskDevice.getMerId());
                            if (wwDevice == null) { //不存在，则跳出
                                continue;
                            }

                            SpeedGroupSendJobDevice speedGroupSendJobDevice = new SpeedGroupSendJobDevice();
                            speedGroupSendJobDevice.setId(IdWorker.getId());
                            speedGroupSendJobDevice.setMerId(speedGroupSendTaskDevice.getMerId());
                            speedGroupSendJobDevice.setJobId(speedGroupSendJob.getId());
                            speedGroupSendJobDevice.setDeviceUniqueId(speedGroupSendTaskDevice.getDeviceUniqueId());
                            speedGroupSendJobDevice.setDeviceId(wwDevice.getDeviceId());
                            speedGroupSendJobDevice.setCreateTime(now);
                            speedGroupSendJobDevice.setUpdateTime(now);
                            speedGroupSendJobDeviceMapper.insertSelective(speedGroupSendJobDevice);
                        }
                    }

                } catch (Exception e) {
                    status.setRollbackOnly();
                    logger.error(e.getMessage());
                }
                return null;
            }
        });

    }


    public boolean verifyTime(SpeedGroupSendTask groupSendTask) {

        if (groupSendTask == null) {
            return false;
        }

        //类型(0-立即发送；1-定时发送；2-每天发送；3-每周发送；4-每月发送)
        Integer type = Tools.getInteger(groupSendTask.getType());

        //只验证循环发送任务
        if (!Lists.newArrayList(2, 3, 4).contains(type)) {
            return false;
        }

        if (type.intValue() == 3) { //每周发送
            List<Integer> weekList = JSONObject.parseArray(groupSendTask.getWeek(), Integer.class);
            if (weekList == null || weekList.size() == 0) {
                return false;
            }
            //判断发送星期几
            LocalDate date = LocalDate.now();
            int dayOfWeek = date.getDayOfWeek().getValue();
            if (!weekList.contains(dayOfWeek)) {
                return false;
            }
        } else if (type.intValue() == 4) {
            List<Integer> dayList = JSONObject.parseArray(groupSendTask.getDay(), Integer.class);
            if (dayList == null || dayList.size() == 0) {
                return false;
            }
            LocalDate date = LocalDate.now();
            // 获取日
            int dayOfMonth = date.getDayOfMonth();
            if (!dayList.contains(dayOfMonth)) {
                return false;
            }
        }

        //发送时间（HH:mm）
        String time = groupSendTask.getTime();
        if (org.apache.commons.lang3.StringUtils.isBlank(time)) {
            time = "00:00";
        }

        //允许发送区间开始时间=提前30分钟
        LocalTime limitTimeStartLocal = LocalTime.parse(time).minusMinutes(30);
        //允许发送区间结束时间=延后1分钟
        LocalTime limitTimeEndLocal = LocalTime.parse(time).plusMinutes(1);

        //判断当前时间是否在自动任务开启时间区间内
        boolean withinTimeInterval = Tools.isWithinTimeInterval(LocalDateTime.now(), limitTimeStartLocal, limitTimeEndLocal);
        //不在区间内，则跳过
        if (!withinTimeInterval) {
            return false;
        }

        return true;
    }


    @Override
    public Integer getFilterSendTargetNum(SpeedGroupSendTaskDto speedGroupSendTaskDto) {
        Integer total = 0;
        List<Long> deviceUniqueIds = speedGroupSendTaskDto.getSpeedGroupSendTaskDeviceDtoList().stream().map(SpeedGroupSendTaskDeviceDto::getDeviceUniqueId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Integer customerSwitch = Tools.getInteger(speedGroupSendTaskDto.getCustomerSwitch());
        if (customerSwitch != null && customerSwitch == 1) {
            Integer customerType = Tools.getInteger(speedGroupSendTaskDto.getCustomerType());

            if (customerType.intValue() == 0 || customerType.intValue() == 1) {
                CustomerQuery customerQuery = new CustomerQuery();
                customerQuery.setMerId(speedGroupSendTaskDto.getMerId());
                customerQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
                Long idStart = 0L;
                customerQuery.setAsc(true);
                customerQuery.setCurrent(1);
                customerQuery.setSize(50);
                customerQuery.setOrderByField("id");
                customerQuery.setIdStart(idStart);

                String orderBy = OrderByUtil.getOrderBy(customerQuery.getOrderByField(), customerQuery.isAsc());
                PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
                List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
                while (wwCustomerVoList != null && wwCustomerVoList.size() > 0) {
                    for (WwCustomerVo wwCustomerVo : wwCustomerVoList) {
                        try {
                            if (wwCustomerVo.getId().longValue() > idStart.longValue()) {
                                idStart = wwCustomerVo.getId();
                            }
                            //验证客户是否有内部会员内部账号
                            if (StringUtils.isBlank(wwCustomerVo.getExternalUserid())) {
                                continue;
                            }
                            //客户验证结果，默认为通过验证
                            boolean result = true;
                            if (customerType.intValue() == 1) { //按照条件筛选客户，需要验证
                                SpeedGroupSendJobVo speedGroupSendJobVo = new SpeedGroupSendJobVo();
                                BeanUtil.copyProperties(speedGroupSendTaskDto, speedGroupSendJobVo);
                                result = verifyCustomer(speedGroupSendJobVo, wwCustomerVo);
                                //勾选了排除条件
                                if (result && speedGroupSendJobVo.getCustomerExcludeCondition() != null && speedGroupSendJobVo.getCustomerExcludeCondition() == 1) {
                                    boolean ifExclude = excludeCustomer(speedGroupSendJobVo, wwCustomerVo);
                                    if (ifExclude) {
                                        continue;
                                    }
                                }
                            }
                            if (result) {//符合条件，则添加消息
                                total++;
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                    customerQuery.setIdStart(idStart);
                    PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
                    wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
                }
            } else if (customerType.intValue() == 2) {
                //
                List<SpeedGroupSendTaskCustomerDto> speedGroupSendTaskCustomerDtoList = speedGroupSendTaskDto.getSpeedGroupSendTaskCustomerDtoList();
                for (SpeedGroupSendTaskCustomerDto speedGroupSendTaskCustomerDto : speedGroupSendTaskCustomerDtoList) {
                    try {

                        //默认黑名单不通过
                        WwCustomerBlacklist wwCustomerBlacklist = blackListMapper.selectByWxid(speedGroupSendTaskDto.getMerId(), speedGroupSendTaskCustomerDto.getSendWxid());
                        if (wwCustomerBlacklist != null) { //在黑名单中
                            logger.info("黑名单会员wxid={}, merId={}", speedGroupSendTaskCustomerDto.getSendWxid(), speedGroupSendTaskDto.getMerId());
                            continue;
                        }

                        WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(speedGroupSendTaskCustomerDto.getSendWxid(), speedGroupSendTaskCustomerDto.getDeviceUniqueId(), speedGroupSendTaskDto.getMerId());
                        if (wwCustomer != null) {

                            //验证客户是否有内部会员内部账号
                            if (StringUtils.isBlank(wwCustomer.getExternalUserid())) {
                                continue;
                            }
                            WwCustomerVo wwCustomerVo = new WwCustomerVo();
                            BeanUtil.copyProperties(wwCustomer, wwCustomerVo);
                            total++;
                        }
                    } catch (Exception e) {
                        logger.error("--循环选择客户群发消息失败--error={}", e.getMessage(), e);
                    }
                }

            }

        }
        return total;
    }
}